/**
 * weapp-js v2.2.3(2022-4-26)
 * https://codeup.aliyun.com/motigo/motigo/weapp_base
 * Copyright@ 2022 Motigo, Inc.
 * 
 */
const KEYS = [];
const INGORE_KEYS = ['request', 'audio', 'recorder'];

function hasCallback(args) {
    if (!args || typeof args !== 'object') return false;

    const callback = ['success', 'fail', 'complete'];
    for (const m of callback) {
        if (typeof args[m] === 'function') return true;
    }
    return false;
}

function _promisify(func) {
    if (typeof func !== 'function') return fn;
    return (args = {}) =>
        new Promise((resolve, reject) => {
            func(
                Object.assign(args, {
                    success: resolve,
                    fail: reject
                })
            );
        });
}

export function promisifyAll(target = {}) {
    let keys = [];
    for (const key in target) {
        keys.push(key);
    }
    if (KEYS.some(key => Object.getPrototypeOf(target) === Object.getPrototypeOf(key))) {
        // console.log(Object.getOwnPropertyNames(Object.getPrototypeOf(target)));
        keys = keys.concat(Object.getOwnPropertyNames(Object.getPrototypeOf(target)));
    }
    // console.log(keys);
    keys.forEach(key => {
        const fn = target[key];
        if (typeof fn === 'function') {
            if (key.startsWith('_')) {
                // 内部方法，不需兼容promise写法
            } else {
                target[key] = args => {
                    if (hasCallback(args)) {
                        fn.call(target, args);
                    } else {
                        return _promisify(fn.bind(target))(args);
                    }
                };
            }
        } else if (typeof fn === 'object' && fn !== null) {
            if (!INGORE_KEYS.includes(key)) {
                promisifyAll(fn);
            }
        }
    });
}

export const promisify = _promisify;
